package com.gitee.xiao.ai;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 返回录屏视频的Controller，通过调用此接口，前端可以流式的获取到视频文件：
 * @author wang xiao
 * date 2024/7/10
 */
@RestController
public class VideoStreamingController {

    @Autowired
    private ScreenRecordRepository screenRecordRepository;

    @Value("${record.file.path}")
    private String recordPath = "/path/to/record/files";

    @GetMapping("/streaming-record/{recordId}")
    public ResponseEntity<Resource> streamVideo(@PathVariable Long recordId) {

        // 从数据库中检索出录屏记录
        ScreenRecord record = screenRecordRepository.getOne(recordId);

        // 构建录屏文件路径
        Path path = Paths.get(recordPath + record.getFilename());
        Resource resource;
        try {
            resource = new InputStreamResource(Files.newInputStream(path, StandardOpenOption.READ));
            // 以流的形式返回录屏文件
            return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                    .contentType(MediaTypeFactory.getMediaType(resource)
                            .orElse(MediaType.APPLICATION_OCTET_STREAM))
                    .body(resource);
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "无法找到录屏文件！");
        }
    }
}
